<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <div class="tags">
          <el-row>
            <el-col :span="20" style="text-align=right">
              <el-form :model="q" label-width="100px" ref="resetIpt">
                <el-form-item label="标签名称" class="name_p">
                  <el-input class="ipt_w" v-model="q.tagName"> </el-input>
                </el-form-item>
                <el-form-item label="状态" class="state_p">
                  <el-select placeholder="请选择" v-model="q.state">
                    <!-- <el-option v-for="(item,index) in options" :key="index" :label="item.label" :value="item.value"> -->
                    <el-option label="启用" value="1"></el-option>
                    <el-option label="禁用" value="0"></el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <el-button class="btn_clear" @click="clear">清除</el-button>
              <el-button type="primary" @click="search">搜索</el-button>
            </el-col>
            <el-col :span="4">
              <el-link v-if="id" type="primary" @click="backToSub">返回学科</el-link>
              <el-button class="btn" style="text-align=right" type="success" @click="addShow"
                ><i class="el-icon-edit"></i>新增标签</el-button
              >
            </el-col>
          </el-row>
        </div>
        <!-- 消息提示 -->
        <!-- 这里的数据不是写死 -->
        <el-alert :title="`数据一共${total}条`" type="info" show-icon :closable="false"> </el-alert>
        <el-table :data="mylist" style="width: 100%" class="table_top">
          <el-table-column label="序号" type="index" width="100"> </el-table-column>
          <el-table-column label="所属学科" prop="subjectName"> </el-table-column>
          <el-table-column label="标签名称" prop="tagName"> </el-table-column>
          <el-table-column label="创建者" prop="username"> </el-table-column>
          <el-table-column label="创建日期" prop="addDate">
            <template v-slot="{ row }">
              {{ row.addDate | trunDate }}
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="state">
            <template v-slot="{ row }">
              {{ row.state | getValue }}
            </template>
          </el-table-column>
          <el-table-column prop="" label="操作">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="disAble(scope.row)">{{
                scope.row.state === 1 ? '启用' : '禁用'
              }}</el-button>
              <!-- 修改和删除都一样就封装了一个方法 -->
              <el-button type="text" size="small" :disabled="disabled(scope.row.state)" @click="Edit(scope.row)"
                >修改</el-button
              >
              <!-- <el-button type="text" size="small" :disabled="scope.row.state === 1 ? false : true">修改</el-button> -->
              <!-- <el-button type="text" size="small" @click="del(scope.row.id)" :disabled="scope.row.state === 1 ? false : true">删除</el-button> -->
              <el-button type="text" size="small" @click="del(scope.row.id)" :disabled="disabled(scope.row.state)"
                >删除</el-button
              >
              <!-- <el-button type="text" size="small" @click="test">测试</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="pagesizes"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
        <!-- 添加的弹窗 -->
        <el-dialog :title="myform.id ? '编辑' : '新增'" :visible.sync="dialogShow">
          <el-form :model="myform" label-width="100px" :rules="rules" ref="myrefs">
            <el-form-item label="所属学科" prop="subjectID" v-if="!id">
              <!-- <el-input v-model="subjectName"></el-input> -->
              <el-select placeholder="请选择" v-model.number="myform.subjectID">
                <el-option v-for="(item, index) in mydata" :key="index" :label="item.subjectName" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="目录名称" prop="tagName">
              <el-input v-model="myform.tagName" class="ipt_name"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submit">提交</el-button>
            <el-button @click="cancle">取 消</el-button>
          </div>
        </el-dialog>
      </el-card>
    </div>
  </div>
</template>

<script>
import { list, add, remove, changeState, update } from '@/api/hmmm/tags.js' // 标签类接口
import { list as subList } from '@/api/hmmm/subjects.js' // 学科类接口
export default {
  name: 'tags',
  data() {
    return {
      q: {
        page: 1,
        pagesize: 10,
        tagName: '',
        state: null
      },
      // form: {
      //   tagName: '',
      //   state: '',
      //   select: ''
      // },
      mylist: [],
      // options: [
      //   { label: '已启用', value: 1 },
      //   { label: '已禁用', value: 0 }
      // ],
      currentPage: 1,
      pagesizes: [10, 15, 20, 25],
      pagesize: 10,
      total: 0,
      subjectID: '',
      myform: {
        subjectID: '',
        tagName: ''
      },
      dialogShow: false,
      // subject: [],
      rules: {
        subjectID: [
          {
            required: true,
            message: '所属学科不能为空',
            trigger: 'blur'
          }
        ],
        tagName: [
          {
            required: true,
            message: '目录名称不能为空',
            trigger: 'blur'
          }
        ]
      },
      mydata: [],
      isDisable: false,
      // 接受数组传过来state
      state: '',
      id: this.$route.query.id
    }
  },
  created() {
    this.getlist()
    this.getsimple()
    this.haveId()
  },
  methods: {
    // 通过id 去渲染当前的数据
    // 封装的一个方法
    async idData() {
      const res = await list({
        page: this.currentPage,
        pagesize: this.pagesize,
        subjectID: this.id
        // subjectID: this.myform.subjectID
      })
      // console.log(res)
      this.mylist = res.data.items
      // console.log(this.mylist)
      this.total = res.data.counts
    },
    backToSub() {
      this.$router.push('/subjects/list')
    },
    async haveId() {
      if (!this.id) return
      this.idData()
    },
    // 修改
    // 渲染数据
    // 此时需要一个id 就可以用...{} 添加到里面 展开结构
    // 点击编辑打弹出层  现在和添加弹出层是一样的结构和数据 唯一的区别就是id
    Edit(row) {
      this.dialogShow = true
      this.myform = { ...row }
      // const { id, subjectID, tagName } = row

      // console.log(res)
    },
    // test() {
    //   判断里头吧,1会转为true,0会转为false
    //   {} => true
    //   [] => true
    //   function => true
    //   '' => false
    //   NaN/ null/ undefined/ 0 => false
    //   if (0 && 1) {
    //     console.log('转为了true')
    //   } else {
    //     console.log('转为了false')
    //   }
    // },
    async disAble(row) {
      // 发送的如果是1 (true)的话,状态就是已启用,要是0(false)的话,就是已经用
      const { id, state } = row
      const res = await changeState({
        id: id,
        state: +!state
      })
      console.log(res)
      // 发送完请求,修改本地数据中的state, 取反再转为数字型
      this.mylist.forEach(item => {
        if (item.id === id) item.state = +!state
      })

      this.$message.success('操作成功')
    },
    // 按钮禁用
    disabled(state) {
      return !state
    },
    cancle() {
      this.myform = {
        subjectID: '',
        tagName: ''
      }
      this.dialogShow = false
    },
    // 删除
    async del(id) {
      const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result !== 'confirm') return
      const res = await remove({ id })
      console.log(res)
      this.$message.success('删除成功')
      // 问题:只有一条数据时删除后数据显示为空的问题
      // 解决办法:数据只有一条并且当前页>1 ,才让当前页减1
      if (this.mylist.length === 1 && this.currentPage > 1) this.currentPage--
      if (this.id) {
        this.idData()
        // console.log('有id,进来了')
      } else {
        this.getlist()
        // console.log('没id,进来了')
      }
    },
    // 搜索
    search() {
      this.q.page = 1
      this.getlist()
    },
    // 清除数据
    clear() {
      this.q = {
        page: '',
        pagesize: '',
        tagName: '',
        state: null
      }
      this.getlist()
      // this.$refs.resetIpt.resetFields()
    },
    // 提交数据
    submit() {
      this.$refs.myrefs.validate(async valid => {
        if (!valid) return
        if (this.myform.id) {
          await update(this.myform)
        } else {
          if (this.id) this.myform.subjectID = +this.id
          await add(this.myform)
        }

        // await add(this.myform)
        this.$message.success(this.myform.id ? '编辑成功' : '新增成功')
        this.dialogShow = false
        // 清空数据
        this.myform = {}
        // 判断是否从学科进来的
        if (this.id) {
          this.idData()
        } else {
          this.getlist()
        }
      })
    },
    // 点击弹窗新增
    async addShow() {
      this.dialogShow = true
    },
    // 获取列表数据
    async getlist() {
      const res = await list({
        page: this.currentPage,
        pagesize: this.pagesize,
        tagName: this.q.tagName,
        state: this.q.state
        // subjectID: this.myform.subjectID
      })
      // console.log(res)
      this.mylist = res.data.items
      // console.log(this.mylist)
      this.total = res.data.counts
      // this.q = res.data
    },
    // 获取简单列表数据
    async getsimple() {
      const res = await subList()
      this.mydata = res.data.items
      // console.log(res)
    },

    handleSizeChange(size) {
      this.pagesize = size
      this.getlist()
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.getlist()
    }
  }
}
</script>

<style lang="scss" scoped>
.ipt_w {
  width: 200px;
  height: 32px;
}
.btn {
  margin-left: 20px;
}
.name_p {
  float: left;
}
.state_p {
  float: left;
}
.btn_clear {
  margin-left: 20px;
}
.table_top {
  margin-top: 20px;
}
.ipt_name {
  width: 220px;
}
</style>
